package org.orcean.com.web.handler;

import lombok.extern.slf4j.Slf4j;
import org.orcean.com.common.response.Message;
import org.orcean.com.common.response.ResultVo;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author BigKang
 * @Date 2020/1/7 3:11 PM
 * @Summarize 全局异常捕获
 */
@ControllerAdvice
@Slf4j
@Component
public class CustomExceptionHandler {

    /**
     * 捕获全局异常并且返回信息
     * @param request
     * @param response
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public ResultVo exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e){
        for (StackTraceElement element : e.getStackTrace()) {
            if(element.getClassName().equals("org.springframework.web.method.support.InvocableHandlerMethod")){
                break;
            }
            log.error("异常类：{},异常方法：{},异常行数：{}",element.getClassName(),element.getMethodName(),element.getLineNumber());
        }
        log.error("异常类型：{}，异常信息：{}",e.getClass().getName(),e.getMessage());
        log.error("异常请求 {} ：{}",request.getMethod(),request.getRequestURI());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return ResultVo.error(e.getMessage());
    }


    /**
     * 404配置相应
     * @return
     */
    @ExceptionHandler(value = NoHandlerFoundException.class)
    @ResponseBody
    public ResultVo noHandlerFound(HttpServletResponse response){
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return ResultVo.result(HttpServletResponse.SC_NOT_FOUND, Message.NOHANDLER);
    }
}